﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Adapter
{
    /// <summary>
    /// 模拟堆栈的接口 特征：先进先出
    /// </summary>
    interface Istack  // 客户期望的接口
    {
        void Push(object obj);
        object Pop();
        object Peek();
    }

    public class StackArrList : Istack // 适配器
    {

        private ArrayList arrayList = new ArrayList();  //被适配对象  

        public void Push(object obj)
        {
            arrayList.Add(obj);
        }

        public object Pop()
        {
            if (arrayList.Count == 0)
            {
                return null;
            }
            object obj = arrayList[arrayList.Count - 1];
            arrayList.RemoveAt(arrayList.Count - 1);
            return obj;
        }

        public object Peek()
        {
            if (arrayList.Count == 0)
            {
                return null;
            }
            return arrayList[arrayList.Count - 1];
        }

    }

    class ExistingClass
    {
        public int FileInt { get; set; }

        public void Say()
        {
            Console.WriteLine("Hello" + this.FileInt);
        }

    }

    class ExistingClassAdapter : IComparer
    {
        Type type = typeof(ExistingClass);
        public int Compare(object x, object y)
        {
            if (x.GetType() == type && y.GetType() == type)
            {
                ExistingClass xExist = x as ExistingClass;
                ExistingClass yExist = y as ExistingClass;
                if (xExist.FileInt == yExist.FileInt)
                {
                    return 0;
                }
                else if (xExist.FileInt > yExist.FileInt)
                {
                    return 1;
                }
                return -1;
            }
            else
            {
                throw new Exception("类型不匹配");
            }
        }
    }

    public class MySys
    {
        public void Process(ITarget target)
        {
            target.Request();
        }

        public void Sort()
        {
            ExistingClass[] exArr = new ExistingClass[100];
            Random rand = new Random();
            for (int i = 0; i < exArr.Length; i++)
            {
                exArr[i] = new ExistingClass() { FileInt = rand.Next(100) };
            }
            Array.Sort(exArr, new ExistingClassAdapter());
        }
    }

    public interface ITarget
    {
        void Request();
    }

    public class SysAdapter : ITarget
    {
        ExistingClass OldCalss = new ExistingClass() { FileInt = 110 };
        public void Request()
        {
            OldCalss.Say();
        }
    }

}
